package com.example.blog.demos.web.controller;

import com.example.blog.demos.web.enmus.ResultCodeEnum;
import com.example.blog.demos.web.model.Result;
import com.example.blog.demos.web.model.UserInfo;
import com.example.blog.demos.web.service.UserService;
import com.example.blog.demos.web.utils.JwtUtils;
import com.example.blog.demos.web.utils.SecurityUtils;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 接收请求
 * @author Q
 * @create 2025-06-20-16:16
 */
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String userName, String password){
        log.info("用户登录, userName: {}", userName);
        Assert.hasLength(userName, "用户名不能为空");
        Assert.hasLength(password, "密码不能为空");
        //验证账号密码是否正确
        UserInfo userInfo = userService.selectUserInfoByName(userName);
        if (userInfo==null || userInfo.getId()==null){
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "用户不存在");
        }
        if (!SecurityUtils.verify(password, userInfo.getPassword())){
            log.error("密码验证失败");
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "密码错误");
        }
//        if (!password.equals(userInfo.getPassword())){
//            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "密码错误");
//        }
        //账号密码正确的逻辑
        Map<String,Object> cliams = new HashMap<>();
        cliams.put("id", userInfo.getId());
        cliams.put("name", userInfo.getUserName());

        String jwt = JwtUtils.genJwt(cliams);
        return Result.success(jwt);

    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String userToken = request.getHeader("user_token_header");
        //从token中获取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(userToken);
        Assert.notNull(userId, "用户未登录");
        UserInfo userInfo = userService.selectUserInfoById(userId);
        return userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        Assert.notNull(blogId, "博客ID不能为null");
        return userService.selectAuthorInfoByBlogId(blogId);
    }
}
